﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lexer {
	class Node<T> {
		public TokenCreator<T> Callback;

		private Dictionary<CharPattern, Node<T>> outgoing = new Dictionary<CharPattern,Node<T>>();

		public Node<T> getOrCreateOutgoing(CharPattern cp) {
			Node<T> result = null;
			if (outgoing.TryGetValue(cp, out result) == false) {
				result = new Node<T>();
				outgoing[cp] = result;
			}
			if (cp.IsRepeating) result.createSelfLoop(cp);
			return result;
		}

		void createSelfLoop(CharPattern cp) {
			outgoing[cp] = this;
		}

		public Node<T> getOutgoing(char c) {
			var matching = outgoing.Keys.Where(cp => cp.matches(c.ToString())).ToList();
			switch (matching.Count) {
				case 0: return null;
				case 1: return outgoing[matching[0]];
				default: throw new AmbiguousException();
			}
		}
	}
}
